<script setup>
import { ref, toRefs, reactive, computed, onBeforeMount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue';
import { listHandler } from '../../api/Generic'
import { deleteTableRow, object2List, list2Object  } from '../../utils/utils';
import Table from '../components/Table.vue';
import DialogYaml from '../components/DialogYaml.vue'
import { obj2Yaml } from '../../utils/utils';
import { createSecretHandler as createHandler, updateSecretHandler as updateHandler } from '../../api/secret.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  item: {
    type: Object
  }
})
const data = reactive({
  clusterId: '',
  namespace: '',
  item: {// service数据结构定义
    apiVersion: 'v1',
    kind: 'Secret',
    metadata: {
      name: '',
      namespace: '',
      labels: {},
      annotations: {},
    },
    immutable: false,
    stringData: {},
    type: 'Opaque',
  },
  dockerCfg: {
    auths: {},
  },
  options: {
    labelList: [],
    annotationList: [],
    dataList: [],
    immutableDisabled: false,
    rules: {
      name: [
        {required: true, message: 'Secret名称必须值', trigger: 'blur'}
      ]
    },
    secretTypeList: [
      {
        label: '通用类型(默认)',
        value: 'Opaque'
      },
      {
        label: '镜像仓库密钥',
        value: 'kubernetes.io/dockerconfigjson'
      },
      {
        label: '域名证书',
        value: 'kubernetes.io/tls'
      },
    ],
    secretTypeConfig: {
      'Opaque': [],
      'kubernetes.io/dockerconfigjson': [
        {
          'key': 'address',
          'value': '',
        },
        {
          'key': 'username',
          'value': '',
        },
        {
          'key': 'password',
          'value': '',
        },
        {
          'key': 'email',
          'value': '',
        },
      ],
      'kubernetes.io/tls': [
        {
          'key': 'tls.key',
          'value': ''
        },
        {
          'key': 'tls.crt',
          'value': ''
        }
      ]
    }
  }
})
const secretTypeChanged = (val) => {
  console.log("选择的secret类型：",val)
  // 把类型数据赋值到dataList
  data.options.dataList = data.options.secretTypeConfig[val]
}
const itemRef = ref()
const activeName = ref('basic')
const labelConfig = ref('labels')
const yamlContent = ref('')
const showDetail = ref(false)

const submitRollback = (msg) => {
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
      draggable: true,
    }
  ).then(() => {
    // 跳转/service/list
    router.replace({
      path: '/secret/list',
      query: {
        clusterId: data.clusterId,
        namespace: data.namespace
      }
    })
  }).catch(() => {
    return
  })
}

const submitHandler = (tag) => {
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationList)
  const tableData = list2Object(data.options.dataList)
  if(data.item.type == 'kubernetes.io/dockerconfigjson'){
    console.log("密钥配置：",tableData)
    const user_pass = `${tableData.username}:${tableData.password}` // 拼接用户名跟密码
    const auth = btoa(user_pass.trim()) // 使用btoa方法实现base64加密 并trim去掉2边空格
    const authConfig = {}
    const registryConfig = {
      username: tableData.username,
      password: tableData.password,
      email: tableData.email,
      auth: auth
    }
    data.dockerCfg.auths[tableData.address] = registryConfig
    console.log("dockerCfg:",data.dockerCfg)
    if(data.item.stringData == undefined ){data.item.stringData = {}}
    data.item.stringData['.dockerconfigjson'] = JSON.stringify(data.dockerCfg)
  }else{
    data.item.stringData = tableData
  }
  

  if(tag == 'yaml') { // json转yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      item: data.item
    }
    if (props.method != 'Update') {
      createHandler(postData).then((response) => {
        submitRollback(response.data.message)
      })
    } else {
      updateHandler(postData).then((response) => {
        console.log(props.method)
        submitRollback(response.data.message)
      })
    }
  }
}

const submit = (tag) => {
  itemRef.value.validate((valid) => {
    if(!valid){
      ElMessage({
        message: '请完善表单',
        type: "warning"
      })
    }else {
      submitHandler(tag)
    }
  })
  

}

const namespaceChangedHandler = (clusterId, namespace) => {
  console.log('service namespaceChangedHandler', clusterId, namespace)
  data.clusterId = clusterId
  data.namespace = namespace
  data.item.metadata.namespace = namespace
}

onBeforeMount(() => {
  if(props.method != 'Create'){
    data.item = JSON.parse(JSON.stringify(props.item))
    data.options.labelList = object2List(data.item.metadata.labels)
    data.options.annotationList = object2List(data.item.metadata.annotations)
    // 对编辑的数据进行处理
    if (data.item.type == 'kubernetes.io/dockerconfigjson') {
      const dockerCfg = atob(data.item.data['.dockerconfigjson'])
      const dockerCfgObj = JSON.parse(dockerCfg)
      console.log("dockerconfigjson:", dockerCfgObj)
      data.dockerCfg = dockerCfgObj
      const address = Object.keys(dockerCfgObj.auths)[0]
      console.log("address:", address)
      const auth = dockerCfgObj.auths[address]
      const registryConfig = {
        'address': address,
        'username': auth.username,
        'password': auth.password,
        'email': auth.email
      }
      data.options.dataList = object2List(registryConfig)
    }else{
      const base64Data = data.item.data
      for (let [key, value] of Object.entries(base64Data)) {
        const o = {
          key: key,
          value: atob(value) // 解密atob
        }
        data.options.dataList.push(o)
      }
    }
    // data.options.dataList = object2List(data.item.data)
    if (props.method == 'Update' && data.item.immutable) {
      data.options.immutableDisabled = true
    }
    delete data.item.data // 删除data字段
  }
})

const { options, item, clusterId, namespace } = toRefs(data)
</script>

<template>
  <CreateOrEditFrame
  :namespace-readonly="props.method=='Update'"
  :cluster-readonly="props.method=='Update'"
  @namespace-chanaged-rollback="namespaceChangedHandler"
  >
    <template #main>
      <el-form :model="item"
      center
      ref="itemRef"
      >
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="基本配置" name="basic" style="height:360px">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item :rules="options.rules.name" label="Secret名称" prop="metadata.name" required>
                  <el-input :disabled="props.method == 'Update'" v-model="item.metadata.name" style="margin-left: 10px; width: 180px;"></el-input>
                </el-form-item>
              </el-col>


              <el-col :span="6">
                <el-form-item label="类型" prop="">
                  <el-select v-model="item.type" placeholder=""
                  @change="secretTypeChanged">
                    <el-option v-for="item in options.secretTypeList" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>


              <!-- 设置configmap为只读 -->
              <el-col :span="4">
                <el-form-item label="只读" prop="">
                  <el-switch :disabled="options.immutableDisabled" v-model="item.immutable"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>


          <el-tab-pane label="数据配置">
            <Table 
            :list="options.dataList" value-input-type="textarea"
            :rows="1" key-width="320px" :readonly="options.immutableDisabled"
            :key-readonly="item.type != 'Opaque'"
            :show-options="item.type == 'Opaque'"
            >
            </Table>
          </el-tab-pane>


          <el-tab-pane label="注释及标签" name="labels" style="height:360px">
            <el-tabs v-model="labelConfig" tabPosition="left">
              <el-tab-pane label="标签配置" name="labels">
                <Table :list="options.labelList"></Table>
              </el-tab-pane>
              <el-tab-pane label="注解配置" name="annos">
                <Table :list="options.annotationList"></Table>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
        <span style="display: block;margin-top: 30px;" class="span-button">
          <el-button @click="submit('yaml')">yaml</el-button>
          <el-button type="primary" @click="submit()">{{ props.method=="Update"?"更新":"创建" }}</el-button>
        </span>
      </el-form>
    </template>
  </CreateOrEditFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val) => { showDetail = val }"
  >
  </DialogYaml>
</template>

<style scoped>
</style>
